const jwtUtils = require('../utils/jwtUtil')
const redisUtil = require('../utils/redisUtil')
const tools = require('../utils/tools')
const mysqlUtil = require('../utils/mysqlUtil')
/**
 * 登录
 * @param req
 * @param resp
 */
let login = async (req,resp) => {
    let query = req.query;
    let name = query.name;
    let pwd = query.pwd;
    // console.log(`会话id：${req.sessionID}`)
    console.log(`当前全局名字:${global.cname},全局密码:${global.cpwd}`)
    // console.log(`当前会话名字:${req.session.currentName},会话密码:${req.session.currentPwd}`)
    if (name === global.cname && pwd === global.cpwd){
        let captcha =req.query.captcha;
        console.log(captcha);
        await redisUtil.set('captcharedis',captcha);
        if (captcha ==  req.session.captcha) {
            resp.send()
            await redisUtil.set('useInfo',JSON.stringify())
            //let user = {name:'zupeng',school:'FZU',age:20,weight:60,height:170};
            await redisUtil.set(user.id,user,3600)
            resp.send(jwtUtils.sign({id:user.id},global.globalKey,3600));

        }else{
            throw new Error('验证失败')
            return;
        }
    }else {
        throw new Error('用户名或密码错误')
    }
}
/**
 * 注册
 * @param req
 * @param resp
 */
let regist =async (req,resp) => {
    let body = req.body;
    let name = body.name;
    let account = body.account;
    let pwd =body.pwd;
    if (!name || !account || !pwd){
        tools.error(resp,'关键参数丢失')
        return;
    }
    let tmp = await mysqlUtil.exec('select id from user where account = ?',
        mysqlUtil.formatParams(account))
    if (tmp.length != 0) {
        tools.error(resp,'用户名已存在')
        return;
    }
     await mysqlUtil.exec('insert into user(id,name,account,pwd) value(?,?,?,?)',
         mysqlUtil.formatParams(tools.newId(),name,account,pwd));
        global.cname =name;
        global.cpwd = pwd;
    // req.session.currentName = name;
    // req.session.currentPwd = pwd;
    // console.log(`会话id：${req.sessionID}`)
        resp.send('注册成功')
}
let getUserInfo = (req,resp) =>{
    let header = req.headers;
    let token = header.token;
    let cookies=req.cookies;
    redisUtil.get();
    // let zupeng=cookies.zupeng;
    // resp.cookie('zuqiang',new Date().getTime())
    // resp.send({
    //     name:req.query.name,
    //     class:'xunke',
    //     token:token,
    //     zupeng
    // })
}
module.exports = {login,regist,getUserInfo}
